package com.didi.gulimall.ware.service.impl;

import com.didi.gulimall.common.constant.WareConstant;
import com.didi.gulimall.ware.vo.MergeVo;
import com.didi.gulimall.ware.vo.PurchaseDoneVo;
import com.didi.gulimall.ware.vo.PurchaseItemDoneVo;
import com.didi.gulimall.ware.vo.WarehousingVO;
import com.didi.gulimall.ware.entity.PurchaseDetailEntity;
import com.didi.gulimall.ware.service.PurchaseDetailService;
import com.didi.gulimall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.didi.gulimall.common.utils.PageUtils;
import com.didi.gulimall.common.utils.Query;

import com.didi.gulimall.ware.dao.PurchaseDao;
import com.didi.gulimall.ware.entity.PurchaseEntity;
import com.didi.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService detailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        BigDecimal totalPrice = BigDecimal.ZERO;
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        } else {
            PurchaseEntity purchaseEntity = this.baseMapper.selectById(purchaseId);
            totalPrice = purchaseEntity.getAmount();
            if (purchaseEntity.getStatus() != 0 && purchaseEntity.getStatus() != 1) {
                throw new RuntimeException("采购单无效");
            }
        }
        List<Long> items = mergeVo.getItems();
        List<PurchaseDetailEntity> collect = new ArrayList<>();
        for (Long i : items) {
            PurchaseDetailEntity detailEntity = detailService.getById(i);
            Integer skuNum = detailEntity.getSkuNum();
            BigDecimal num = new BigDecimal(skuNum);
            totalPrice = totalPrice.add(detailEntity.getSkuPrice().multiply(num));
            detailEntity.setPurchaseId(purchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            collect.add(detailEntity);
        }
        detailService.updateBatchById(collect);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setAmount(totalPrice);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );
        return new PageUtils(page);
    }

    @Override
    public void received(List<Long> purchases) {
        List<PurchaseEntity> collect = purchases.stream().map(this::getById).filter(item -> {
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).peek(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
        }).collect(Collectors.toList());
        //2、改变采购单的状态
        this.updateBatchById(collect);
        collect.forEach(item -> {
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo doneVo) {
        Long purchaseId = doneVo.getId();
        //2、改变采购项的状态
        Boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        List<WarehousingVO> warehousings = new ArrayList<>();
        for (PurchaseItemDoneVo item : doneVo.getItems()) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                ////3、将成功采购的进行入库
                PurchaseDetailEntity purchaseDetail = detailService.getById(item.getItemId());
                WarehousingVO warehousing = new WarehousingVO();
                warehousing.setSkuId(purchaseDetail.getSkuId());
                warehousing.setSkuNum(purchaseDetail.getSkuNum());
                warehousing.setWareId(purchaseDetail.getWareId());
                warehousings.add(warehousing);
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);
        wareSkuService.addStock(warehousings);
        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}